package com.hippoframework.bean;
import java.beans.Introspector;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ClassUtil;
import com.hippoframework.annotation.Autowired;
import com.hippoframework.annotation.Component;
import com.hippoframework.bean.processor.BeanPostProcessor;
import com.hippoframework.exception.BeanNotOfRequiredTypeException;
import com.hippoframework.exception.BeansException;
import com.hippoframework.exception.NoSuchBeanDefinitionException;
import com.hippoframework.exception.NoUniqueBeanDefinitionException;
import com.hippoframework.utils.Assert;
import com.hippoframework.utils.ClassUtils;
import com.hippoframework.utils.StringUtils;
import lombok.Getter;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;

/**
 * 默认Bean工厂实现
 *
 * @author YichuanWang
 * @date 12/26/2019 5:44 PM
 */
@Slf4j
public class DefaultBeanFactory implements BeanFactory {

    /**
     * 缓存，存储完成初始化的单例Bean
     */
    @Getter
    private final Map<String, Object> singletonBeanMap = new ConcurrentHashMap<>(256);
    /**
     * Bean定义（模板）缓存
     */
    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
    /**
     * Bean实现缓存，Key为待注入的抽象类名（ClassName），Value为实际注入的实现类名(BeanName)
     */
    private final Map<String, String> inheritBeanMap = new HashMap<>(64);

    /**
     * Bean后置处理器，于依赖注入后依次执行
     */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>(1);

    private Set<String> propsBean;

    public static DefaultBeanFactory init() {
        log.info("init default bean factory...");
        return new DefaultBeanFactory();
    }

    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        beanPostProcessors.add(beanPostProcessor);
    }

    @Override
    public Map<String, BeanDefinition> getBeanDefinitions() {
        return beanDefinitionMap;
    }

    public void addBean(@NonNull String name, @NonNull Object bean) {
        singletonBeanMap.put(name, bean);
    }

    public Object getBean(@NonNull String name) {
        return this.doGetBean(name);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getBean(@NonNull String name, @NonNull Class<T> requiredType) throws BeansException {
        Object bean = getBean(name);
        if (requiredType != null && !requiredType.isInstance(bean)) {
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
        return (T) bean;
    }

    @Override
    public <T> T getBean(@NonNull Class<T> requiredType) {
        String[] beanNames = getBeanNamesForType(requiredType);
        if (beanNames.length == 1) {
            return getBean(beanNames[0], requiredType);
        } else if (beanNames.length > 1) {
            throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
        } else {
            throw new NoSuchBeanDefinitionException(requiredType);
        }

    }

    public String[] getBeanNamesForType(@NonNull Class<?> type) {
        List<String> matches = new ArrayList<>();
        for (Map.Entry<String, Object> entry : singletonBeanMap.entrySet()) {
            String name = entry.getKey();
            Object beanInstance = entry.getValue();
            if (beanInstance.getClass() == type) {
                matches.add(name);
            }
        }
        return StringUtils.toStringArray(matches);
    }

    private Object doGetBean(@NonNull String beanName) {
        return getSingleton(beanName);
    }

    /**
     * 获得单例Bean
     * <p>若此Bean未创建，则将其创建后放入earlySingletonMap中
     */
    private Object getSingleton(String beanName) {
        Object singletonObject = this.singletonBeanMap.get(beanName);
        if (singletonObject == null) {
            singletonObject = createBean(beanName);
            singletonBeanMap.put(beanName, singletonObject);
        }
        return singletonObject;
    }

    @SneakyThrows
    public Object createBeanInstance(@NonNull BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Assert.notNull(beanClass);
        if (!Modifier.isPublic(beanClass.getModifiers())) {
            throw new BeansException("Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
        }
        return beanClass.newInstance();
    }

    private Object createBean(String beanName) {
        return createBeanInstance(beanDefinitionMap.get(beanName));
    }

    public void registerBeanDefinition(@NonNull String beanName, @NonNull BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    public BeanDefinition getBeanDefinition(@NonNull String beanName) {
        return beanDefinitionMap.get(beanName);
    }

    public boolean containsBeanDefinition(@NonNull String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public void doRegisterDefinition(Class<?> cls, GenericBeanDefinition definition) {
        BeanDefinition existed = getBeanDefinition(Introspector.decapitalize(cls.getSimpleName()));
        if (existed != null && existed.getFactoryBean() != null) {
            return;
        }
        this.parseComponent(cls, definition);
        log.info("注册Component:{}，beanName：{}", cls.getName(), definition.getBeanName());
        registerBeanDefinition(definition.getBeanName(), definition);
    }

    /**
     * 解析Component
     */
    @SneakyThrows
    private void parseComponent(Class<?> cls, GenericBeanDefinition definition) {
        Optional.ofNullable(cls.getAnnotation(Component.class)).ifPresent(e -> definition.setBeanName(e.name()));
        if (StringUtils.isEmpty(definition.getBeanName())) {
            definition.setBeanName(Introspector.decapitalize(cls.getSimpleName()));
        }
        definition.setBeanClass(cls);
        definition.setBeanClassName(cls.getSimpleName());
        definition.setAbstractFlag(ClassUtil.isAbstract(cls));
        if (!definition.isAbstract()) {
            Field[] declaredFields = ClassUtil.getDeclaredFields(cls);
            definition.setDependsOn(Arrays.stream(declaredFields)
                                          .filter(e -> e.isAnnotationPresent(Autowired.class))
                                          .map(e -> new DependencyDescriptor(e, true, cls))
                                          .collect(Collectors.toList()));

        }
    }

    /**
     * 查找抽象类的实现Bean，若同时找到多个结果，则以最后找到的结果为准
     * <p>除非其中某个Bean设置了isPrimary=true，若有多个isPrimary=true的Bean，则以第一个为准
     *
     * @param injectableField 待注入抽象field
     * @return BeanName
     */
    private String findImplBean(Field injectableField) {
        Class<?> clazz = injectableField.getType();
        if (inheritBeanMap.containsKey(clazz.getSimpleName())) {
            return inheritBeanMap.get(clazz.getSimpleName());
        }
        BeanDefinition inheritDefinition = null;
        for (BeanDefinition definition : beanDefinitionMap.values()) {
            if (ClassUtils.isInjectable(definition.getBeanClass(), injectableField, true)) {
                inheritDefinition = definition;
                if (definition.isPrimary()) {
                    break;
                }
            }
        }
        if (inheritDefinition == null) {
            throw new NoSuchBeanDefinitionException(clazz);
        }
        log.info("为抽象类{}找到Bean实现{}", clazz.getSimpleName(), inheritDefinition.getBeanName());
        inheritBeanMap.put(clazz.getSimpleName(), inheritDefinition.getBeanName());
        return inheritDefinition.getBeanName();
    }

    /**
     * 根据BeanFactory中的BeanDefinitionMap注册bean，并存放到BeanMap中
     */
    public void registerBeans() {
        //注册Bean
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            if (!beanDefinition.isAbstract() && beanDefinition.isSingleton() && !singletonBeanMap.containsKey(beanName)
                && beanDefinition.getFactoryBean() == null) {
                Object beanInstance = createBeanInstance(beanDefinition);
                addBean(beanName, beanInstance);
            }
            FactoryBean<?> factoryBean = beanDefinition.getFactoryBean();
            if (beanDefinition.getFactoryBean() != null) {
                addBean(beanName, factoryBean.getObject());
                if (beanDefinition.isAbstract()) {
                    inheritBeanMap.put(beanDefinition.getBeanClassName(), beanName);
                }
            }
        });
        //注入Bean依赖
        log.info("开始执行依赖注入...");
        beanDefinitionMap.values().stream().filter(e -> CollectionUtil.isNotEmpty(e.getDependsOn())).forEach(e -> {
            List<DependencyDescriptor> dependsOn = e.getDependsOn();
            for (DependencyDescriptor descriptor : dependsOn) {
                Field field = descriptor.getField();
                String injectedBeanName = descriptor.getFieldName();
                if (ClassUtil.isAbstract(field.getType())) {
                    injectedBeanName = this.findImplBean(field);
                }
                try {
                    FieldUtils.writeField(field, singletonBeanMap.get(e.getBeanName()), singletonBeanMap.get(injectedBeanName), true);
                } catch (IllegalAccessException ex) {
                    log.error(ex.getMessage(), ex);
                }
            }
        });
    }

    /**
     * 执行Bean后置处理器
     */
    public void doPostProcessInit() {
        for (Map.Entry<String, Object> entry : singletonBeanMap.entrySet()) {
            for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
                beanPostProcessor.doProcessBeforeInit(entry.getValue(), entry.getKey());
            }
        }
    }

}
